<template>
    <div class="transfer-create-page">
      <div class="header">
        <span>新增调拨</span>
        <el-button type="text" @click="refresh">刷新</el-button>
      </div>
  
      <el-form :model="transferForm" class="transfer-form" label-width="100px">
        <el-form-item label="调拨单号">
          <el-input
            disabled
            v-model="transferForm.allocateNum"
            placeholder="可不填写，自动生成"
          ></el-input>
        </el-form-item>
  
        <el-form-item label="*调拨仓库" required>
          <el-select
            v-model="transferForm.alllocation"
            placeholder="请选择调拨仓库"
          >
            <el-option label="仓库1" value="仓库1"></el-option>
            <el-option label="仓库3" value="仓库3"></el-option>
          </el-select>
        </el-form-item>
  
        <el-form-item label="关联订单号">
          <el-input v-model="transferForm.pRelatNumber"></el-input>
        </el-form-item>
  
        <el-form-item label="制单人">
          <el-input v-model="transferForm.creator" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="transferForm.shenRember"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="300"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
  
      <div class="product-info-section">
        <span>产品信息</span>
        <br />
        <br />
        <br />
        <el-button type="primary" @click="openProductSelector"
          >+ 新增产品</el-button
        >
      </div>
  
      <el-table :data="productList" border class="product-table">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          label="产品名称"
          prop="pRelatuionshipName"
        ></el-table-column>
        <el-table-column label="产品编码" prop="pRelatNumber"></el-table-column>
        <el-table-column
          label="规格"
          prop="pRelatuionshipGuige"
        ></el-table-column>
        <el-table-column label="批次" prop="batch">
          <template #default="scope">
            <el-input v-model="scope.row.batch" placeholder="输入批次"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="单价"
          prop="pRelatuionshipPrice"
        ></el-table-column>
        <el-table-column label="数量">
          <template #default="scope">
            <el-input
              v-model="scope.row.quantity"
              placeholder="输入数量"
              type="number"
              @input="calculateTotal(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="总价" prop="totQuantity"></el-table-column>
        <el-table-column label="库位" prop="warehouseLocation"
          >3号仓库.默认正式库位</el-table-column
        >
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="text" size="small" @click="deleteProduct(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
  
      <div class="button-group">
        <el-button type="primary" @click="submitTransfer">提交</el-button>
        <el-button @click="cancelTransfer">取消</el-button>
      </div>
    </div>
    <el-dialog
      title="选择产品"
      ref="dialogRef"
      v-model="dialogVisible"
      width="1200px"
    >
      <el-form :model="searchParams" class="search-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编号">
              <el-input
                v-model="searchParams.productCode"
                placeholder="请输入编码"
                class="form-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称">
              <el-input
                v-model="searchParams.productName"
                placeholder="请输入名称"
                class="form-input"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="search-button-container">
        <el-button type="primary" @click="searchProducts" class="search-button">
          搜索
        </el-button>
      </div>
      <br />
      <el-table
        @selection-change="handleSelectionChange"
        :data="dialogProductList"
        border
        class="product-table"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          label="产品名称"
          prop="pRelatuionshipName"
        ></el-table-column>
        <el-table-column label="产品编码" prop="pRelatNumber"></el-table-column>
        <el-table-column
          label="规格"
          prop="pRelatuionshipGuige"
        ></el-table-column>
        <el-table-column label="类别" prop="productCatgoryId"></el-table-column>
        <el-table-column
          label="单价"
          prop="pRelatuionshipPrice"
        ></el-table-column>
        <el-table-column label="单位" prop="seadId"></el-table-column>
      </el-table>
      <br />
      <el-pagination
        v-model:current-page="form1.PageIndex"
        v-model:page-size="form1.PageSize"
        :page-sizes="[1, 3, 15, 100]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form1.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <br />
      <div class="button-group">
        <el-button @click="closeDialog" class="action-button"> 关闭 </el-button>
        <el-button type="primary" @click="confirmSelection" class="action-button">
          选择
        </el-button>
      </div>
    </el-dialog>
  </template>
  <script setup lang="ts">
  import { ElMessageBox, ElMessage } from "element-plus";
  import { reactive, onMounted, ref } from "vue";
  import axios from "axios";
  import { useRouter, useRoute } from "vue-router";
  import dayjs from "dayjs";
import { KongaUrl } from "@/axios/axiosHelp";
  const router = useRouter();
  const route = useRoute();
  const form1 = reactive({
    TotalCount: 0,
    PageCount: 0,
    PageSize: 5,
    PageIndex: 1,
  });
  const handleSizeChange = (newSize) => {
    form1.PageSize = newSize;
  };
  
  const handleCurrentChange = (newPage) => {
    form1.PageIndex = newPage;
  };
  const openProductSelector = () => {
    dialogVisible.value = true;
    searchProducts();
  };
  const productList = ref([]);
  const dialogProductList = ref([]);
  
  const dialogVisible = ref(false);
  const searchProducts = () => {
    KongaUrl
      .get("/wangcong/api/Whouase/GetPRelatuionships", {
        params: {
          PageSize: form1.PageSize,
          PageIndex: form1.PageIndex,
        },
      })
      .then((res) => {
        dialogProductList.value = res.data.data.list;
        form1.TotalCount = res.data.data.totalCount;
        form1.PageCount = res.data.data.PageCount;
      })
      .catch((error) => {
        console.error("获取产品列表失败", error);
      });
  };
  const deleteProduct = (product) => {
    ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const index = productList.value.indexOf(product);
        if (index !== -1) {
          productList.value.splice(index, 1);
        }
      })
      .catch(() => {});
  };
  
  const dialogSelection = ref<any[]>([]);
  const handleSelectionChange = (val: any[]) => {
    dialogSelection.value = val;
  };
  const confirmSelection = () => {
    const selectedRows = dialogSelection.value;
    if (selectedRows.length === 0) {
      ElMessage.warning("请选择产品");
      return;
    }
    selectedRows.forEach((selectedProduct) => {
      productList.value.push({
        pRelatuionshipName: selectedProduct.pRelatuionshipName,
        pRelatuionshipPrice: selectedProduct.pRelatuionshipPrice,
        storageLocationId: selectedProduct.storageLocationId,
        batch: selectedProduct.specification,
        pRelatuionshipGuige: selectedProduct.pRelatuionshipGuige,
        pRelatuionshipId: selectedProduct.pRelatuionshipId,
        pRelatNumber: selectedProduct.pRelatNumber,
        quantity: "",
        totQuantity: "",
      });
    });
    closeDialog();
  };
  const calculateTotal = (row: any) => {
    if (row.quantity !== "" && row.pRelatuionshipPrice !== "") {
      row.totQuantity = (
        Number(row.quantity) * Number(row.pRelatuionshipPrice)
      ).toFixed(2);
    } else {
      row.totQuantity = "";
    }
  };
  const searchParams = ref({
    productCode: "",
    productName: "",
  });
  const closeDialog = () => {
    dialogVisible.value = false;
    searchParams.value.productCode = "";
    searchParams.value.productName = "";
    dialogProductList.value.forEach((row) => {
      row._checked = false;
    });
  };
  // 调拨表单数据
  const transferForm = ref({
    pRelatNumber: "",
    allocateNum: "",
    associatedNum: "",
    alllocation: "",
    creator: "陈平安",
    shenRember: "",
  });
  // 刷新页面
  const refresh = () => {
    // 这里可添加实际刷新逻辑，如重新获取数据
    ElMessage.success("页面已刷新");
  };
  // 提交调拨
  const submitTransfer = async () => {
    // 添加必填字段验证
  
    if (productList.value.length === 0) {
      ElMessage.error("请至少添加一个产品");
      return;
    }
  
    const payload = {
      allocateNum: transferForm.value.allocateNum,
      alllocation: transferForm.value.alllocation,
      creator: transferForm.value.creator,
      shenRember: transferForm.value.shenRember,
      pRelatNumber: transferForm.value.pRelatNumber,
      ProDto: productList.value.map((item) => ({
        pRelatuionshipName: item.pRelatuionshipName,
        pRelatuionshipPrice: item.pRelatuionshipPrice,
        storageLocationId: item.storageLocationId
          ? Number(item.storageLocationId)
          : 0,
        batch: item.batch.toString(),
        pRelatuionshipGuige: item.pRelatuionshipGuige,
        pRelatuionshipId: item.pRelatuionshipId,
        pRelatNumber: item.pRelatNumber,
        quantity: item.quantity.toString(), // 转换为字符串
        totQuantity: item.totQuantity.toString(), // 转换为字符串
      })),
    };
  
    try {
      const res = await KongaUrl.post(
        "/wangcong1/api/WHouase/AddAllocate",
        payload
      );
  
      if (res.data.code === 200) {
        ElMessage.success("创建成功");
        router.push("/GetAllocate");
      } else {
        ElMessage.error(res.data.message);
      }
    } catch (error) {
      console.error("API Error:", error);
      if (error.response) {
        ElMessage.error(`请求失败: ${error.response.data.title}`);
      } else {
        ElMessage.error("网络错误，请检查连接");
      }
    }
  };
  
  // 取消调拨
  const cancelTransfer = () => {
    // 这里添加实际取消逻辑，如重置表单等
    ElMessage.success("操作已取消");
  };
  const generateTwelveDigitNumber = () => {
    const characters = "0123456789";
    let result = "";
    for (let i = 0; i < 12; i++) {
      // 生成12位数字
      result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
  };
  onMounted(() => {
    transferForm.value.allocateNum = generateTwelveDigitNumber();
  });
  </script>
  <style scoped>
  /* 基础容器样式 */
  .transfer-create-page {
    padding: 24px;
    background: #f8fafc;
    min-height: 100vh;
    box-sizing: border-box;
  }
  
  /* 头部美化 */
  .header {
    margin-bottom: 28px;
    padding: 16px 24px;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;
  }
  
  .header span {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
    position: relative;
    padding-left: 12px;
  }
  
  .header span::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 20px;
    background: #3b82f6;
    border-radius: 2px;
  }
  
  /* 表单美化 */
  .transfer-form {
    margin-bottom: 24px;
    padding: 24px;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;
  }
  
  .transfer-form .el-form-item {
    margin-bottom: 20px;
  }
  
  .transfer-form .el-input__inner,
  .transfer-form .el-select__wrapper,
  .transfer-form .el-textarea__inner {
    border-radius: 8px;
    transition: all 0.3s ease;
  }
  
  .transfer-form .el-input.is-disabled .el-input__wrapper {
    background-color: #f8fafc;
  }
  
  .transfer-form .el-input__inner:focus,
  .transfer-form .el-select__wrapper:hover,
  .transfer-form .el-textarea__inner:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  }
  
  /* 产品信息区 */
  .product-info-section {
    padding: 16px 24px;
    margin: 24px 0;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;
  }
  
  .product-info-section span {
    font-size: 16px;
    font-weight: 500;
    color: #1e293b;
  }
  
  .product-info-section .el-button {
    padding: 10px 20px;
    border-radius: 8px;
    background: linear-gradient(135deg, #10b981, #059669);
    border: none;
    transition: all 0.3s ease;
  }
  
  .product-info-section .el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 6px rgba(16, 185, 129, 0.2);
  }
  
  /* 表格美化 */
  .product-table {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 24px;
  }
  
  .product-table >>> .el-table__header th {
    background: #f1f5f9;
    color: #64748b;
    font-weight: 600;
  }
  
  .product-table >>> .el-table__row--striped {
    background: #f8fafc;
  }
  
  .product-table >>> .el-table__row:hover td {
    background: #f1f5f9 !important;
  }
  
  .product-table >>> .el-input__wrapper {
    border-radius: 6px;
  }
  
  /* 操作按钮 */
  .product-table >>> .cell .el-button {
    padding: 6px 12px;
    border-radius: 6px;
    transition: all 0.2s ease;
  }
  
  .product-table >>> .cell .el-button:hover {
    background: #f1f5f9;
    transform: translateY(-1px);
  }
  
  /* 按钮组 */
  .button-group {
    margin-top: 32px;
    text-align: center;
  }
  
  .button-group .el-button {
    width: 140px;
    padding: 12px 24px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
  }
  
  .button-group .el-button--primary {
    background: linear-gradient(135deg, #3b82f6, #2563eb);
    border: none;
  }
  
  .button-group .el-button--primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 6px rgba(59, 130, 246, 0.2);
  }
  
  .button-group .el-button:not(.el-button--primary) {
    border: 1px solid #cbd5e1;
    background: #ffffff;
  }
  
  .button-group .el-button:not(.el-button--primary):hover {
    border-color: #3b82f6;
    color: #3b82f6;
    background: #f8fafc;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .transfer-create-page {
      padding: 16px;
    }
  
    .header,
    .transfer-form,
    .product-info-section {
      padding: 16px;
      border-radius: 8px;
    }
  
    .product-table >>> .el-table__cell {
      padding: 12px 8px;
    }
  
    .button-group .el-button {
      width: 100%;
      margin-bottom: 12px;
    }
  }
  </style>